#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define SIZE 1024

void Writer(int wfd)
{
    string s = "hello, I am child";
    pid_t self = getpid();
    int number = 0;
    char buff[SIZE] = {0};
    while (true)
    {
        buff[0] = 0;
        snprintf(buff, sizeof(buff), "%s-%d-%d", s.c_str(), self, number++);
        write(wfd, buff, strlen(buff));
        // cout << number << endl;
        // if (number >= 5) break;
        sleep(1);
    }
}

void Reader(int rfd)
{
    char buff[SIZE] = {0};
    int cnt = 5;
    while (cnt--)
    {
        //sleep(3);
        buff[0] = 0;
        ssize_t n = read(rfd, buff, sizeof(buff)-1);
        if (n > 0)
        {
            buff[n] = 0;
            cout << "father get a message[" << getpid() << "]# " << buff << endl;
        }
        else if (n == 0)
        {
            cout << "father read file done!" << endl;
            break;
        }
        else break;
    }
}
int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0) return 1;

    pid_t id = fork();
    if (id < 0) return 2;
    if (id == 0)
    {
        close(pipefd[0]);
        Writer(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    
    close(pipefd[1]);
    Reader(pipefd[0]);
    close(pipefd[0]); // 父进程关闭读端

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid < 0) return 3;
    printf("father wait %d success, exit code: %d, exit signal: %d\n", rid, (status>>8)&0xff, status&0x7f);
    close(pipefd[0]);
    return 0;
}